"""
======================
Author: 柠檬班-小简
Time: 2022/10/24 20:30
Project: day5_framwork_V3
Company: 湖南零檬信息技术有限公司
======================
"""
"""
jsonpath - json对象里面，进行搜索。
官方地址：https://goessner.net/articles/JsonPath/
jsonpath在线练习地址：http://jsonpath.com/
                   http://www.e123456.com/aaaphp/online/jsonpath/

第三方库 jsonpath
pip install jsonpath

提取出来的值 = jsonpath(python的字典对象, jsonpath表达式)
提取到了，返回的是列表。
没有提取到，返回的是False
"""
from jsonpath import jsonpath
# mybooks = { "store": {
#     "book": [
#       { "category": "reference",
#         "author": "Nigel Rees",
#         "title": "Sayings of the Century",
#         "price": 8.95
#       },
#       { "category": "fiction",
#         "author": "Evelyn Waugh",
#         "title": "Sword of Honour",
#         "price": 12.99
#       },
#       { "category": "fiction",
#         "author": "Herman Melville",
#         "title": "Moby Dick",
#         "isbn": "0-553-21311-3",
#         "price": 8.99
#       },
#       { "category": "fiction",
#         "author": "J. R. R. Tolkien",
#         "title": "The Lord of the Rings",
#         "isbn": "0-395-19395-8",
#         "price": 22.99
#       }
#     ],
#     "bicycle": {
#       "color": "red",
#       "price": 19.95
#     }
#   }
# }
#
# value = jsonpath(mybooks, "$..book[?(@.price<10)]")
# print(value)

# 模拟响应结果数据
resp_json = {"access_token":"c2368537-07a7-4da9-bb5d-7b21ce5a5699","token_type":"bearer","refresh_token":"dc2150a7-eb49-4f74-b11e-3248fb15e654","expires_in":1295999}
# 从excel当中读取出来的提取表达式
extract_expr = '{"token":"$..access_token","new_token":"$..refresh_token"}'

new_dict = {}
# 转成字典 ，并且遍历。
for key,jsonpath_expr in eval(extract_expr).items():
    print(key, jsonpath_expr)
    # 根据jsonpath表达式，从响应结果当中，提取对应的值。
    # 注意：如果提取到了值，返回的是列表。
    value_list = jsonpath(resp_json, jsonpath_expr)
    if value_list:
        new_dict[key] = value_list[0]
print(new_dict)